#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argv, char **argc)
{
    FILE *fp = fopen("2.txt", "a+");
    if(fp == NULL)
    {
        perror("fopen fail");
        exit(1);
    }

    #if 1
    //将格式化数据写入指定文件或者内存
    //int sprintf(char *str, const char *format, ...);
    //int snprintf(char *str, size_t size, const char *format, ...);
    //int fprintf(FILE *stream, const char *format, ...);
    char name[10] = "小强";
    int age = 10;
    char addr[50] = "广州";

    fprintf(fp,"名字:%s 年龄:%d 籍贯:%s\n", name, age, addr);
    fprintf(fp,"名字:%s 年龄:%d 籍贯:%s\n", name, age, addr);

    char *pbuf = (char *)malloc(sizeof(char)*1024);

    //格式化字符串保存到特定数组或者缓冲区 即内存
    snprintf(pbuf, 1024,"名字:%s 年龄:%d 籍贯:%s\n", name, age, addr);
    printf("%s\n",pbuf);

    free(pbuf);

    #endif


    #if 1
    char name1[10];
    int age1;
    char addr1[50];
    //从指定文件或内存中读取格式化数据
    //int scanf(const char *format, ...);
    //int fscanf(FILE *stream, const char *format, ...);
    //int sscanf(const char *str, const char *format, ...);
    
    //保证文件光标在文件头
    int ret = fseek(fp, 0, SEEK_SET);
    if(ret < 0)
    {
        perror("fseek fail");
        exit(1);
    }

    while(1)
    {    
        ret = fscanf(fp,"名字:%s 年龄:%d 籍贯:%s\n", name1, &age1, addr1);
        if(ret == EOF)
        {
            printf("文件已经读取到末尾\n");
            break;
        }
        printf("名字:%s 年龄:%d 籍贯:%s\n", name1, age1, addr1);
    }

    //格式化读取内存里的特定数据到变量中。
    //printf将上面家族的#if 0 设置为 1
    sscanf(pbuf, "名字:%s 年龄:%d 籍贯:%s\n",name1, &age1, addr1);
    printf("名字:%s 年龄:%d 籍贯:%s\n", name1, age1, addr1);


    #endif




    return 0;
}